package com.panopset.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.panopset.compat.Strings;

/**
 * Stores contents of a text file in a ArrayList.
 * 
 * @author Karl Dinwiddie
 * 
 */
public final class TextFileList {

	private final File f;

	/**
	 * Text file lines.
	 */
	private final List<String> lines = new ArrayList<String>();

	/**
	 * @return Text file lines.
	 */
	public List<String> getLines() {
		return lines;
	}

	/**
	 * 
	 * @param file
	 *            Text file.
	 */
	public TextFileList(final File file) {
		f = file;
		if (!f.canRead()) {
			return;
		}
		try {
			

        	// TODO put in try / close when we hit Java 7.
			
			FileReader fr = new FileReader(file);
		
				BufferedReader br = new BufferedReader(fr);
			String s = br.readLine();
			while (s != null) {
				lines.add(s);
				s = br.readLine();
			}
			
			br.close();
			fr.close();
		} catch (final IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	public void flush() {
		try {

        	// TODO put in try / close when we hit Java 7.
			
			BufferedWriter bw = new BufferedWriter(new FileWriter(f)); 
			final String eol = Strings.getEol();
			for (String s : lines) {
				bw.write(s);
				bw.write(eol);
			}
			bw.flush();
			bw.close();
			
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}
}
